//玩家端组局
import {
	add
} from '@/api/crud.js'
let WebIM = require("@/utils/WebIM")["default"];
const disp = require("@/utils/broadcast");
import {
	mapGetters
} from 'vuex'
export default {
	computed: {
		...mapGetters(['loginForm', 'disable']),
		uid() {
			return this.loginForm.uid;
		},
		//信用分低于60分，抢车计时5秒，低于40分8秒，低于20分10秒，0分不准抢车
		carTimeMax() {
			const {
				creditScore
			} = this.loginForm
			if (creditScore >= 60) return 3
			if (creditScore >= 40 && creditScore < 60) return 5
			if (creditScore >= 20 && creditScore < 40) return 8
			if (creditScore < 20) return 10
			return 1
		}
	},
	data() {
		return {
			cancelCar: '取消组局将会记录毁车次数，确定取消吗？', //发行取消发车提示
			storeCancelCar: '若组局前1小时内下车会影响你的信用分哦！', //玩家下车提示
			confirmCar: '正在抢车...',
			modelFlag: false,
			closeModalTips: '',
			activeItem: {},
			confirmCarTime: 3,
			modelType: '',
			initBusFlag: false,
			intoCarLoading: false,
			outCarLoading: false
		}
	},
	created() {
		this.initBus()
		this.confirmCarTime = this.carTimeMax;
	},
	destroyed() {
		uni.$off('busNotice')
		uni.$off('cancelCar')
		uni.$off('startCar')
	},
	onShow() {
		this.initCarBus()
	},
	methods: {
		initCarBus() {
			this.initBusFlag && this.initBus()
			this.initBusFlag = true;
		},
		initBus() {
			if (!this.uid) return false;
			uni.$on('busNotice', newValue => {
				if (newValue.customEvent !== 'gather_game_tips') return false;
				const {
					gatherGameId
				} = newValue
				let groupItem = null;
				if (this.tabs) {
					groupItem = this.$refs.mescroll[this.tabIndex].dataList.find(val => val.id == gatherGameId)
				}
				if (this.dataList) groupItem = this.dataList.find(val => val.id == gatherGameId)
				if (this.item && this.item.id == gatherGameId) groupItem = this.item;
				if (groupItem) {
					this.$set(groupItem, 'participate', newValue.userSmallDtos.length)
					this.$set(groupItem, 'userSmallDtos', newValue.userSmallDtos)
					const flag = newValue.userSmallDtos.some(val => val.uid == this.uid);
					this.$set(groupItem, 'isIntoGame', flag)
					//如果是详情页 则发送通知
					if (this.item && (this.item.id == gatherGameId)) uni.$emit('isIntoGame', flag);
					this.teamChange && this.teamChange()
				}
			})
			uni.$on('cancelCar', res => {
				console.log('cancelCar')
				if (res.customEvent !== 'gather_game_tips') return false;
				this.cancelCarcallback && this.cancelCarcallback(res)
			})
			uni.$on('startCar', res => {
				console.log('startCar')
				if (res.customEvent !== 'gather_game_tips') return false;
				this.startCarcallback && this.startCarcallback(res)
			})
			disp.fire("em.chat.readyNum");
		},
		//邀请玩家
		shareStore(item) {
			const {id:teamId,productId,productName:name,type:isOnline,intoPayMoney,onlineIntoPayMoney} = item;
			const gamePrice = isOnline===1 ? onlineIntoPayMoney : intoPayMoney
			this.$u.route({
				url:'/pagesA/shareCar/shareCar',
				params:{
					teamId,
					productId,
					name,
					gamePrice,
					isOnline
				}
			})
		},
		isBillVaildate() {
			if (this.loginForm.ticket) return Promise.resolve();
			uni.showModal({
				content: '请先验票后再操作！',
				confirmText: "去验票",
				title: '温馨提示',
				success: ({
					confirm
				}) => {
					if (confirm) {
						this.$u.route({
							url: "/pagesA/validateBill/validateBill"
						})
					}
				}
			})
			return Promise.reject()
		},
		//验证是否完善资料
		isSettingInfo() {
			if (this.disable) return Promise.resolve();
			uni.showModal({
				content: '请先完善资料后再操作！',
				confirmText: "去完善",
				title: '温馨提示',
				success: ({
					confirm
				}) => {
					if (confirm) {
						this.$u.route({
							url: "/pages/setting/setting"
						})
					}
				}
			})
			return Promise.reject()
		},
		//全局上车统一管理
		async pushCar(type, item) {
			if (!this.uid) {
				this.loginFlagFn()
				return false;
			}
			const creditScore = this.loginForm.creditScore
			if (creditScore == 0) {
				this.$u.toast('信用分太低了，不准上车了！')
				return false;
			}
			try {
				await this.isBillVaildate()
				await this.isSettingInfo()
				this.modelFlag = true;
				this.activeItem = item;
				this.modelType = type;
				this.closeModalTips = this[type];
				this.timeDown()
			} catch (e) {
				//TODO handle the exception
			}
		},
		loginFlagFn() {
			this.modelFlag = true;
			this.modelType = 'loginFlag';
			this.closeModalTips = '请先登录才能上车哦';
		},
		//清空倒计时状态
		clearTime() {
			if (this.modelType === 'confirmCar') {
				if (this.downTimer) clearTimeout(this.downTimer);
				this.confirmCarTime = this.carTimeMax;
				this.downTimer = null;
				this.closeModalTips = '正在抢车...';
				this.modelType = ''
			}
		},
		timeDown() {
			this.closeModalTips = `正在抢车...${this.confirmCarTime}s`
			this.downTimer = setTimeout(async () => {
				if (this.confirmCarTime == 1) {
					try {
						await this.confirmCarFn(this.activeItem)
						this.clearTime()
						this.$u.toast('上车成功，已加入群聊');
						disp.fire("em.chat.readyNum");
						setTimeout(() => {
							this.intoCar && this.intoCar(this.activeItem) //上车回调
						}, 1000)
					} catch (e) {
						if (this.downTimer) clearTimeout(this.downTimer);
						this.confirmCarTime = this.carTimeMax;
						this.downTimer = null;
					}
					return false;
				}
				--this.confirmCarTime;
				this.timeDown()
			}, 1000);
		},
		async confirmCarFn(item) {
			console.log(item)
			try {
				this.intoCarLoading = true;
				await add({
					singleData: this.$store.getters.loginForm.uid + '',
					showLoading: true,
					type: 'single' //不是对象
				}, 'gatherGame', 'shopApi', `into/${item.teamId}`)
				this.modelFlag = false;
				this.intoCarLoading = false;
				return Promise.resolve()
			} catch (e) {
				//TODO handle the exception
				console.log(e)
				uni.hideToast();
				this.closeModalTips = e.message || '太多人啦，没挤上！'
				this.modelType = 'rejectFlag'
				this.intoCarLoading = false;
				return Promise.reject(e)
			}
		},
		//下车或取消发车
		async closeCar(type, item) {
			try {
				// await this.isBillVaildate()
				// await this.isSettingInfo()
				this.closeModalTips = this[type];
				this.modelFlag = true;
				this.modelType = '';
				console.log(item)
				this.activeItem = item;
			} catch (e) {
				//TODO handle the exception
			}
		},
		confirmClose() {
			if (this.modelType === 'rejectFlag') {
				this.modelFlag = false;
				return false;
			}
			if (this.modelType === 'loginFlag') {
				this.modelFlag = false;
				this.$u.route({
					url: "/pagesB/register/register"
				})
				return false;
			}
			if (this.modelType === 'cancelCarFlag') {
				this.$u.route({
					type: 'back'
				})
				return false;
			}
			if (this.modelType === 'startCarFlag') {
				this.$u.route({
					type: 'relaunch',
					url: "/page/carTime/carTime",
					params: {
						id: this.item.id
					}
				})
				return false;
			}
			this.outCarLoading = true
			const {uid,dmUid,id} = this.activeItem
			const url = uid == this.loginForm.uid || dmUid=== this.loginForm.uid ? 'cancelGame' : 'outOff';
			add(this.loginForm.uid + '', 'gatherGame', this.apiModule, url + '/' + id).then(res => {
				this.outCarLoading = false
				this.cancelCarcallback && this.cancelCarcallback(this.activeItem) //取消发车回调
			}).catch(() => {
				this.outCarLoading = false
			})
		}
	}
}
